import { Breadcrumb, Table, Space, Button, TableProps, Modal, Cascader, Row, message } from 'antd';
import React, { FC } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  FormPanel,
  type FormPanelObject,
  FormPanelStatus,
  FormPanelBtnDisplay,
  FormPanelBtnAlign,
  InputType,
  ExtendReader,
  Utils,
} from 'lfun-bg-comp';
import _ from 'lodash';
import dayjs from 'dayjs';
import { PageContainer } from '@/component/page-container';
import { PAGINATIONCONFIG } from '@/constant/page';
import utils, { getPathRoot } from '@/utils';
import { GENDER } from '@/constant/basicOptions';
import { getStuInfoList, temporaryStudyCancel } from '@/service/student/instudent';
import { searchSchool } from '@/service/unit/school';
import { getGradeClassOptions } from '@/service/options';
import { STUDENT_APPROVALATATUS, STU_CHANGE_TYPE } from '@/constant/studentOptions';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';

const list = [
  {
    title: '',
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
    inputs: [
      {
        label: '姓名',
        name: 'student_name',
        key: 'student_name',
        textRange: [0, 20],
      },
      {
        label: '身份证件号码',
        name: 'id_number',
        key: 'id_number',
        inputType: InputType.text,
        relationFields: ['birthday', 'student_gender'],
        textRange: [0, 30],
        ruleType: (formObjectPanel: FormPanelObject) => {
          const id_type = formObjectPanel.getFieldValue('id_type');
          if (id_type === 'resident_id_card') {
            return 'cnPeopleNo';
          }
          return '';
        },
        renderValidate: (formOjbectPanel: FormPanelObject) => {
          const id_type = formOjbectPanel.getFieldValue('id_type');
          if (id_type === 'resident_id_card') {
            return ExtendReader.validateCnPeopleNo(
              formOjbectPanel.getFieldValue('id_number'),
              formOjbectPanel.getFieldValue('birthday'),
              formOjbectPanel.getFieldValue('student_gender')
            );
          }
          return '';
        },
      },
      {
        label: '申请时间',
        name: 'operation_time',
        key: 'operation_time',
        inputType: InputType.dateRange,
        formatSubmitValue: (value, formPanelObject: FormPanelObject) => {
          ExtendReader.formatSubmitValueByDateRange(value, formPanelObject, 'operation_time');
          return null;
        },
      },
    ],
  },
];

const Groups: FC = () => {
  const navigate = useNavigate();
  const [value, setValue] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(10);
  const [pageIndex, setPageIndex] = React.useState(1);
  const [loading, setLoading] = React.useState(false);
  //const [condition, setCondition] = React.useState<any>({ audit_status: 'needaudit' });
  const [cur, setCur] = React.useState<any>();
  //const [curForm, setCurForm] = React.useState<any>();
  const [curFormPanelObject, setCurFormPanelObject] = React.useState<any>();
  const [visible, setVisible] = React.useState(false);
  const isSchool = Utils.getProps('isSchool');

  const searchFunc = async (params, pageIndex, pageSize) => {
    setLoading(true);
    const param: any = {
      ...params,
    };
    if (params.class_id && params.class_id.length > 1) {
      param.class_id = params.class_id[1];
    }
    const r = await getStuInfoList(param, pageIndex, pageSize);
    if (r.success) {
      setValue(r.data.items);
      setTotal(r.data.total);
      setPageIndex(pageIndex);
      setPageSize(pageSize);
    } else if (curFormPanelObject) {
      curFormPanelObject.reVaildation(r);
    }
    setLoading(false);
  };

  const handleCancel = (record: any) => {
    Modal.confirm({
      title: '取消临时就读',
      content: `是否取消${record.student_name || ''}的临时就读信息?`,
      onOk: async () => {
        const res = await temporaryStudyCancel(record.id);
        if (res.success) {
          message.success('取消临时就读成功');
          searchFunc({}, 1, pageSize);
        }
      },
    });
  };

  const columns: TableProps['columns'] = [
    {
      title: '姓名',
      dataIndex: 'student_name',
      key: 'student_name',
      width: 150,
      fixed: 'left',
    },
    {
      title: '身份证件号码',
      dataIndex: 'id_number',
      key: 'id_number',
      width: 150,
    },
    {
      title: '性别',
      dataIndex: 'student_gender',
      key: 'student_gender',
      width: 80,
      render: (text: any) => {
        return _.find(GENDER, { value: String(text) })?.label;
      },
    },
    {
      title: '所在界别',
      dataIndex: 'origin_session_name',
      key: 'origin_session_name',
    },
    {
      title: '所在年级',
      dataIndex: 'origin_grade_name',
      key: 'origin_grade_name',
    },
    {
      title: '所在班级',
      dataIndex: 'origin_class_name',
      key: 'origin_class_name',
    },
    {
      title: '原学籍学校',
      dataIndex: 'origin_school_name',
      key: 'origin_school_name',
    },
    {
      title: '就读界别',
      dataIndex: 'session_name',
      key: 'session_name',
    },
    {
      title: '就读年级',
      dataIndex: 'grade_name',
      key: 'grade_name',
    },
    {
      title: '就读班级',
      dataIndex: 'class_name',
      key: 'class_name',
    },
    {
      title: '申请人',
      dataIndex: 'apply_user',
      key: 'apply_user',
      width: 100,
    },
    {
      title: '申请时间',
      dataIndex: 'apply_time',
      key: 'apply_time',
      width: 150,
      render: (text, record) => {
        return record.transaction_time && <span>{dayjs(record.transaction_time).format('YYYY-MM-DD HH:mm:ss')}</span>;
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      fixed: 'right',
      //width: 200,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (_text, record) => (
        <Space>
          <PermissionButton permission="temporary_study_view">
            <Button type="link" onClick={() => navigate(`${getPathRoot()}/instudent/emporaryBorrowing/${record.id}`)}>
              查看
            </Button>
          </PermissionButton>
          {isSchool && (
            <PermissionButton permission="temporary_study_cancel">
              <Button type="link" onClick={() => handleCancel(record)}>
                取消临时就读
              </Button>
            </PermissionButton>
          )}
        </Space>
      ),
    },
  ];

  const handleView = record => {
    setCur({ ...record, transaction_type: record?.transaction_type?.split(',') });
    setVisible(true);
    console.log('查看', record);
  };

  React.useEffect(() => {
    searchFunc({}, 1, pageSize);
  }, []);

  const pageChange = (pageIndex, pageSize) => {
    searchFunc(curFormPanelObject?.getFieldsValue(), pageSize, pageIndex);
    setPageIndex(pageIndex);
    setPageSize(pageSize);
  };
  return (
    <PageContainer header={<Breadcrumb items={[{ title: '异动管理' }]} />}>
      <FormPanel
        btnsAlign={FormPanelBtnAlign.right}
        restBtnText="重置"
        submitBtnText="查询"
        onLoad={(formPanelObject: FormPanelObject) => {
          setCurFormPanelObject(formPanelObject);
        }}
        onFinish={(formPanelObject: FormPanelObject) => {
          searchFunc({ ...formPanelObject.getFieldsValue() }, 1, pageSize);
        }}
        template={list}
      />
      <Row style={{ margin: '20px 0' }}>
        {isSchool && (
          <PermissionButton permission="temporary_study_start">
            <Button type="primary" onClick={() => navigate(`${getPathRoot()}/instudent/emporaryBorrowing/create`)}>
              发起临时就读
            </Button>
          </PermissionButton>
        )}
      </Row>
      <Table
        dataSource={value}
        columns={columns}
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
    </PageContainer>
  );
};

export default Groups;
